<?php

/**
 * Dashboard class
 *
 * @author Tareq Hasan
 * @package WP User Frontend
 */
class WPUF_Dashboard {

    function __construct() {
        add_shortcode( 'wpuf_dashboard', array($this, 'shortcode') );
    }

    /**
     * Handle's user dashboard functionality
     *
     * Insert shortcode [wpuf_dashboard] in a page to
     * show the user dashboard
     *
     * @since 0.1
     */
    function shortcode( $atts ) {

        extract( shortcode_atts( array('post_type' => 'post'), $atts ) );

        ob_start();

        if ( is_user_logged_in() ) {
            $this->post_listing( $post_type );
        } else {
            printf( __( "This page is restricted. Please %s to view this page.", 'wpuf' ), wp_loginout( curPageURL(), false ) );
        }

        $content = ob_get_contents();
        ob_end_clean();

        return $content;
    }

    /**
     * List's all the posts by the user
     *
     * @global object $wpdb
     * @global object $userdata
     */
    function post_listing( $post_type ) {
        global $wpdb, $userdata, $post;

        $userdata = get_userdata( $userdata->ID );
        $pagenum = isset( $_GET['pagenum'] ) ? intval( $_GET['pagenum'] ) : 1;

        //delete post
        if ( isset( $_REQUEST['action'] ) && $_REQUEST['action'] == "del" ) {
            $this->delete_post();
        }

        //show delete success message
        if ( isset( $_GET['msg'] ) && $_GET['msg'] == 'deleted' ) {
            echo '<div class="success">' . __( 'Post Deleted', 'wpuf' ) . '</div>';
        }
		
		// RUN QUERY SO WE CAN COLLECT AP /SSA ID'S IN THE LOOP
		if ( is_ap() ) {
			$args = array(
				'post_status' => array('draft', 'future', 'pending', 'publish'),
				'post_type' => $post_type,
				'posts_per_page' => wpuf_get_option( 'per_page', 10 ),
				'paged' => $pagenum,
				'meta_key' => 'apID',
				'meta_value' => get_current_user_id(),
			);
		} else {
			$args = array(
				'post_status' => array('draft', 'future', 'pending', 'publish'),
				'post_type' => $post_type,
				'posts_per_page' => wpuf_get_option( 'per_page', 10 ),
				'paged' => $pagenum,
				'author' => get_current_user_id(),
			);
		}
        $dashboard_query = new WP_Query( $args );
		
        $post_type_obj = get_post_type_object( $post_type );
        ?>

        <h2 class="page-head">
            <span class="colour"><?php printf( __( "%s's Dashboard", 'wpuf' ), $userdata->display_name ); ?></span>
        </h2>
        
        <?php // LISTING FILTERING
		
			// SOME HELPER FUNCTIONS
				$dashURL = site_url('manage-listings');
				$dashQURL = $dashURL . '?filter=true';
				function selectedOption() { echo ' selected="selected"'; }
				
			// GET PREVIOUS QUERY PARAMETERS
				// STATUS
					$QueryStatus = array();
					if ( isset($_GET['status']) ) {
						$statusVal = $_GET['status'];
						$statusQStr = '&status=' . $statusVal;
						$QueryStatus = array(
							'key' => 'listingStatus',
							'value' => $statusVal,
							'compare' => 'LIKE'
						);
					} else {
						$statusVal = '';
					}
				// REQUIRED DOCUMENTS
					$QueryReqDocs = array();
					if ( isset($_GET['reqDocs']) ) {
						$reqDocsVal = $_GET['reqDocs'];
						$reqDocsQStr = '&reqDocs=' . $reqDocsVal;
						if ( $reqDocsVal == 0 ) { $reqDocsVal = false; } // FOR SOME ODD REASON '1' for 'true' works, but '0' for 'false' RETURNS NO RESULTS WITH WP_QUERY META QUERY - I THINK VALUES ARE STORED AS TRUE=TRUE / FALSE=0
						$QueryReqDocs = array(
							'key' => 'reqDocsMissing',
							'value' => $reqDocsVal,
							'compare' => '='
						);
					} else {
							$reqDocsVal = '';
					}
				// SSA / AP
					if ( isset($_GET['User']) ) {
						$UserVal = $_GET['User'];
						$UserQStr = '&User=' . $UserVal;
						$QueryUserID = $UserVal;
					} else {
						$UserVal = '';
					}
				// GET USERS FOR USER FILTER
					// GET AP's FOR AP FILTER
						if ( is_ssa() ) {
							$users = array();
							if ( $dashboard_query->have_posts() ) {
								while ($dashboard_query->have_posts()) {
									$dashboard_query->the_post();
									// GATHER AP ID's
									$ap = get_user_by( 'id', get_post_meta($post->ID, 'apID', true) );
									$users[$ap->ID] = $ap->display_name;
								}
							}
							asort($users);
					// GET AP's FOR AP FILTER
						} elseif ( is_ap() ) {
							$users = array();
							if ( $dashboard_query->have_posts() ) {
								while ($dashboard_query->have_posts()) {
									$dashboard_query->the_post();
									// GATHER AP ID's
									$ap = get_user_by( 'id', $post->post_author );
									$users[$ap->ID] = $ap->display_name;
								}
							}
							asort($users);
					}
				// RATING
					/*$QueryRating = array();
					if ( isset($_GET['rating']) ) {
						$ratingVal = $_GET['rating'];
						$ratingQStr = '&rating=' . $ratingVal;
						$QueryratingID = $ratingVal;
						$QueryRating = array(
							'key' => 'listingRating',
							'value' => $ratingVal,
							'compare' => '='
						);
					} else {
						$ratingVal = '';
					}*/
				// ORDERBY AND ORDER FILTERS
					// ORDERBY
						if ( isset($_GET['orderBy']) ) {
							$orderByVal = $_GET['orderBy'];
							$QueryOrderBy = $orderByVal;
							$orderByQStr = '&orderBy=' . $orderByVal;
						}
					// ORDER
						if ( isset($_GET['order']) ) {
							$orderVal = $_GET['order'];
							$orderQStr = '&order=' . $orderVal;
						} else {
							$orderVal = 'DESC';
						}
				// SHOW X LISTINGS PER PAGE
					if ( isset($_GET['show']) ) {
						$showVal = $_GET['show'];
						$showQStr = '&show=' . $showVal;
					} else {
						$showVal = '10';
					}
			
			// RE-QUERY WITH NEW PARAMS	
				if ( is_ap() ) { // FOR AGENT PARTNERS
					$QueryMetaUserID = array(
						'key' => 'apID',
						'value' => get_current_user_id(),
						'compare' => '='
					);
					$meta_query = array( $QueryStatus, $QueryReqDocs, $QueryMetaUserID );
					if ( $orderByVal == 'user' ) {
						$QueryOrderBy = 'author';
					} elseif ( $orderByVal == 'status' ) {
						$QueryMetaKey = 'listingStatus';
						$QueryOrderBy = 'meta_value';
					} elseif ( $orderByVal == 'reqDocs' ) {
						$QueryMetaKey = 'reqDocsMissing';
						$QueryOrderBy = 'meta_value';
					} elseif ( $orderByVal == 'rating' ) {
						$QueryMetaKey = 'listingRating';
						$QueryOrderBy = 'meta_value_num';
					}
					$args = array(
						'author' => $QueryUserID,
						'post_status' => array('draft', 'future', 'pending', 'publish'),
						'post_type' => $post_type,
						'posts_per_page' => $showVal,
						'paged' => $pagenum,
						'meta_key' => $QueryMetaKey,
						'meta_query' => $meta_query,
						'orderby' => $QueryOrderBy,
						'order' => $orderVal
					);
				} else { // FOR SHORT SALE ASSISTANTS
					$QueryMetaUserID = array(
						'key' => 'apID',
						'value' => $QueryUserID,
						'compare' => '='
					);
					$meta_query = array( $QueryMetaUserID, $QueryStatus, $QueryReqDocs, $QueryRating );
					if ( $orderByVal == 'user' ) {
						$QueryMetaKey = 'apDisplayName';
						$QueryOrderBy = 'meta_value';
					} elseif ( $orderByVal == 'status' ) {
						$QueryMetaKey = 'listingStatus';
						$QueryOrderBy = 'meta_value';
					} elseif ( $orderByVal == 'reqDocs' ) {
						$QueryMetaKey = 'reqDocsMissing';
						$QueryOrderBy = 'meta_value';
					} elseif ( $orderByVal == 'rating' ) {
						$QueryMetaKey = 'listingRating';
						$QueryOrderBy = 'meta_value_num';
					}
					$args = array(
						'author' => get_current_user_id(),
						'post_status' => array('draft', 'future', 'pending', 'publish'),
						'post_type' => $post_type,
						'posts_per_page' => $showVal,
						'paged' => $pagenum,
						'meta_key' => $QueryMetaKey,
						'meta_query' => $meta_query,
						'orderby' => $QueryOrderBy,
						'order' => $orderVal
					);
				}
				$dashboard_query = new WP_Query( $args );
        // END LISTING FILTERING ?>
        
        <?php if ( wpuf_get_option( 'show_post_count' ) == 'on' ) { ?>
            <div class="post_count"><?php echo '<span>' . $dashboard_query->found_posts . '</span> Listings found'; ?></div>
        <?php } ?>
        <div id="numOfListings">
            <!-- LISTINGS PER PAGE -->
            <select onchange="window.location.href = '<?php echo $dashQURL . '\'+$(this).val()+\'' . $statusQStr . $reqDocsQStr . $UserQStr . $orderByQStr . $orderQStr . "'"; ?>;">
                <option value="">Show</option>
                <option value="&show=10"<?php if ( $showVal == '10' ) { selectedOption(); } ?>>10 Listings</option>
                <option value="&show=25"<?php if ( $showVal == '25' ) { selectedOption(); } ?>>25 Listings</option>
                <option value="&show=50"<?php if ( $showVal == '50' ) { selectedOption(); } ?>>50 Listings</option>
                <option value="&show=100"<?php if ( $showVal == '100' ) { selectedOption(); } ?>>100 Listings</option>
                <!-- DISABLED BECAUSE IT MESSES UP THE POSTS FOUND COUNT <option value="&show=-1"<?php if ( $showVal == '-1' ) { selectedOption(); } ?>>All Listings</option>-->
            </select>
		</div>
        
        <div id="listingDashFilter">
            <span>Show Listings by </span>
            <!-- STATUS -->
            <select onchange="window.location.href = '<?php echo $dashQURL . $showQStr . '\'+$(this).val()+\'' . $reqDocsQStr . $UserQStr . $orderByQStr . $orderQStr . "'"; ?>;">
                <option value="">Status</option>
                <option value="&status=Listing submitted"<?php if ( $statusVal == 'Listing submitted' ) { selectedOption(); } ?>>Listing submitted</option>
                <option value="&status=Offer submitted"<?php if ( $statusVal == 'Offer submitted' ) { selectedOption(); } ?>>Offer submitted</option>
                <option value="&status=Closed"<?php if ( $statusVal == 'Closed' ) { selectedOption(); } ?>>Closed</option>
            </select>
            <!-- reqDocs -->
            <select onchange="window.location.href = '<?php echo $dashQURL . $showQStr . $statusQStr . '\'+$(this).val()+\'' . $UserQStr . $orderByQStr . $orderQStr . "'"; ?>;">
                <option value="">Documents</option>
                <option value="&reqDocs=0"<?php if ( $reqDocsVal == '0' ) { selectedOption(); } ?>>Has Required Documents</option>
                <option value="&reqDocs=1"<?php if ( $reqDocsVal == '1' ) { selectedOption(); } ?>>Missing Required Documents</option>
            </select>
            <!-- User -->
            <select onchange="window.location.href = '<?php echo $dashQURL . $showQStr . $statusQStr . $reqDocsQStr . '\'+$(this).val()+\'' . $orderByQStr . $orderQStr . "'"; ?>;">
                <option value=""><?php if ( is_ssa() ) { echo 'Agent / Partner'; } else { echo 'Short Sale Assistant'; } ?></option>
                <?php
					foreach ( $users as $key => $val ) {
						echo '<option value="&User=' . $key . '"';
						if ( $UserVal == $key ) { selectedOption(); }
						echo '>' . $val . '</option>';
					}
				?>
            </select>
            <a href="<?php echo $dashURL; ?>">Clear</a>
        </div>

        <?php do_action( 'wpuf_dashboard_top', $userdata->ID, $post_type_obj ) ?>

        <?php if ( $dashboard_query->have_posts() ) { ?>

            <?php
            $featured_img = wpuf_get_option( 'show_ft_image' );
            $featured_img_size = wpuf_get_option( 'ft_img_size' );
            $charging_enabled = wpuf_get_option( 'charge_posting' );
            ?>
            <table id="listingDash" class="wpuf-table" cellpadding="0" cellspacing="0">
                <thead>
                    <tr>
						<?php
							// FILTER INDICATORS
								$up = '<img src="' . get_bloginfo( 'template_directory' ) . '/images/sort-arrows.gif" width="11" height="11"/>';
								$down = '<img src="' . get_bloginfo( 'template_directory' ) . '/images/sort-arrows.gif" width="11" height="11"/>';
							
							// TITLE / LISTING
								echo '<th id="title"><a href="' . $dashQURL . $showQStr . $statusQStr . $reqDocsQStr . $UserQStr . '&orderBy=title';
								if ( $orderByVal == 'title' ) {
									if ( $orderVal == 'ASC' ) {
										echo '&order=DESC">View listing dtails</a> ' . $down . '</th>';
									} else {
										echo '&order=ASC">View listing dtails</a> ' . $up . '</th>';
									}
								} else {
									echo '&order=ASC">View listing dtails</a></th>';
								}
							// SSA / AP
								if ( is_ap() ) {
									echo '<th id="user"><a href="' . $dashQURL . $showQStr . $statusQStr . $reqDocsQStr . $UserQStr . '&orderBy=user';
									if ( $orderByVal == 'user' ) {
										if ( $orderVal == 'ASC' ) { echo '&order=DESC">SSA</a> ' . $up . '</th>'; } else { echo '&order=ASC">SSA</a> ' . $down . '</th>'; }
									} else {
										echo '&order=DESC">SSA</a></th>';
									}
								} else {
									echo '<th id="user"><a href="' . $dashQURL . $showQStr . $statusQStr . $reqDocsQStr . $UserQStr . '&orderBy=user';
									if ( $orderByVal == 'user' ) {
										if ( $orderVal == 'ASC' ) { echo '&order=DESC">AP</a> ' . $up . '</th>'; } else { echo '&order=ASC">AP</a> ' . $down . '</th>'; }
									} else {
										echo '&order=ASC">AP</a></th>';
									}
								}
							// STATUS
								echo '<th id="status"><a href="' . $dashQURL . $showQStr . $statusQStr . $reqDocsQStr . $UserQStr . '&orderBy=status';
								if ( $orderByVal == 'status' ) {
									if ( $orderVal == 'ASC' ) { echo '&order=DESC">Status</a> ' . $up . '</th>'; } else { echo '&order=ASC">Status</a> ' . $down . '</th>'; }
								} else {
									echo '&order=DESC">Status</a></th>';
								}
							// REQ DOCS
								echo '<th id="reqDocs"><a href="' . $dashQURL . $showQStr . $statusQStr . $reqDocsQStr . $UserQStr . '&orderBy=reqDocs';
								if ( $orderByVal == 'reqDocs' ) {
									if ( $orderVal == 'ASC' ) { echo '&order=DESC">Req Docs Submitted</a> ' . $up . '</th>'; } else { echo '&order=ASC">Req Docs Submitted</a> ' . $down . '</th>'; }
								} else {
									echo '&order=ASC">Req Docs Submitted</a></th>';
								}
							// ACCESS LINK
								echo '<th id="accessKey">Access Link';
								echo '<a href="' . site_url() . '/wp-content/themes/master/toolTips/accessLinks.html?width=375" class="jTip" id="one" name="What are Access Links?">?</a>';
								echo '</th>';
							// RATING
								if ( is_ap() ) {
									echo '<th id="ratings"><a href="' . $dashQURL . $showQStr . $statusQStr . $reqDocsQStr . $UserQStr . '&orderBy=rating';
									if ( $orderByVal == 'rating' ) {
										if ( $orderVal == 'ASC' ) { echo '&order=DESC">SSA Rating</a> ' . $up . '</th>'; } else { echo '&order=ASC">SSA Rating</a> ' . $down . '</th>'; }
									} else {
										echo '&order=DESC">SSA Rating</a></th>';
									}
								} else {
									echo '<th id="ratings"><a href="' . $dashQURL . $showQStr . $statusQStr . $reqDocsQStr . $UserQStr . '&orderBy=rating';
									if ( $orderByVal == 'rating' ) {
										if ( $orderVal == 'ASC' ) { echo '&order=DESC">AP Rating</a> ' . $up . '</th>'; } else { echo '&order=ASC">AP Rating</a> ' . $down . '</th>'; }
									} else {
										echo '&order=DESC">AP Rating</a></th>';
									}
								}
							// OPTIONS
								echo '<th id="options">Update listing</th>';
						?>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    while ($dashboard_query->have_posts()) {
                        $dashboard_query->the_post();
                        ?>
                        <tr>
						<?php //----- TITLE / LISTING -----// ?>
                            <td class="title"><div>
                            	<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                            </div></td>
						<?php //----- SSA / AP -----// ?>
                            <td class="user"><div>
                                <?php if ( is_ap() ) { 
									echo bp_core_get_userlink(get_the_author_meta('ID'));
								} else {
									$ap = get_user_by('id', get_post_meta($post->ID, 'apID', true));
									echo $ap->display_name;
								} ?>
                            </div></td>
						<?php //----- STATUS -----// ?>
                            <td class="status"><div>
                                <?php echo get_post_meta( $post->ID, 'listingStatus', true ) ?>
                            </div></td>
						<?php //----- REQ DOCS -----// ?>
                            <td class="reqDocs"><div>
                                <?php
								if ( get_post_meta( $post->ID, 'documentTracking', true ) != 'noTracking' ) {
									if ( get_post_meta( $post->ID, 'reqDocsMissing', true ) ) {
										echo '<img src="' . get_bloginfo( 'template_directory' ) . '/images/docsRedX.png" width="20" height="20" />'; // SHOW RED X
									} else {
										echo '<img src="' . get_bloginfo( 'template_directory' ) . '/images/docsGreenCheck.png" width="20" height="20" />'; // SHOW GREEN CHECK
									}
								} else {
									echo 'No tracking';
								}
								?>
                            </div></td>
						<?php //----- ACCESS LINK -----// ?>
                            <td class="accessKey"><div>
								<?php
                                    $edit_page = (int) wpuf_get_option( 'edit_page_id' );
                                    $url = get_permalink( $edit_page );
                                ?>
                                <script type="text/javascript">
									jQuery(document).ready(function($) {
										$('a#clip<?php echo $post->ID; ?>Link').zclip({
											path:'<?php bloginfo( 'template_directory' ); ?>/scripts/ZeroClipboard.swf',
											copy:function(){return $('p#link<?php echo $post->ID; ?>Str').text();}
										});
									});
                                </script>
                                <p id="link<?php echo $post->ID; ?>Str" style="display:none;"><?php echo $url . '?pid=' . $post->ID . '&access=' . get_post_meta( $post->ID, 'accessKey', true ); ?></p>
                            	<a id="clip<?php echo $post->ID; ?>Link" class="zClip" href="#">click to copy</a>
                                <br />
                            	<a href="<?php echo $url . '?pid=' . $post->ID . '&access=' . get_post_meta( $post->ID, 'accessKey', true ); ?>" target="_blank">preview link</a>
                            </div></td>
						<?php //----- RATING -----// ?>
                            <td class="ratings"><div>
								<?php
									$listingStatus = get_post_meta( $post->ID, 'listingStatus', true );
									if ( $listingStatus == 'Closed' ) {
					 					echo '<div style="width:90px;">';
											//if ( is_ap() ) { echo '<a href="' . get_permalink() . '">'; }
												if ( is_ap() ) {
													rate_listing( $post->ID, false, false );
												}
												if ( is_ssa() ) {
													listing_rating_show( $post->ID );
												}
											//if ( is_ap() ) { echo '</a>'; }
										echo '</div>';
									} else {
										echo 'Not closed';
									}
								?>
                            </div></td>
						<?php //----- OPTIONS -----// ?>
                            <td class="options"><div>
                                <a href="<?php echo wp_nonce_url( $url . '?pid=' . $post->ID, 'wpuf_edit' ); ?>">Edit details /<br />Submit docs</a>
                                <?php /*if ( wpuf_get_option( 'enable_post_del' ) == 'yes' ) { ?>
                                    <a href="<?php echo wp_nonce_url( "?action=del&pid=" . $post->ID, 'wpuf_del' ) ?>" onclick="return confirm('Are you sure to delete this post?');"><span style="color: red;"><?php _e( 'Delete', 'wpuf' ); ?></span></a>
                                <?php }*/ ?>
                            </div></td>
                       </tr>
                    <?php } ?>
                </tbody>
            </table>

            <div class="wpuf-pagination">
                <?php
                $pagination = paginate_links( array(
                    'base' => add_query_arg( 'pagenum', '%#%' ),
                    'format' => '',
                    'prev_text' => __( '&laquo;', 'wpuf' ),
                    'next_text' => __( '&raquo;', 'wpuf' ),
                    'total' => $dashboard_query->max_num_pages,
                    'current' => $pagenum
                        ) );

                if ( $pagination ) {
                    echo $pagination;
                }
                ?>
            </div>

            <?php
        } else {
            echo '<div style="clear:both;border-top: 1px solid #E7E7E7;margin-bottom:10px;"></div><h4>No Listings found...</h4>';
            do_action( 'wpuf_dashboard_nopost', $userdata->ID, $post_type_obj );
        }

        do_action( 'wpuf_dashboard_bottom', $userdata->ID, $post_type_obj );
        ?>

        <?php
        //$this->user_info();
    }

    /**
     * Show user info on dashboard
     */
    function user_info() {
        global $userdata;

        if ( wpuf_get_option( 'show_user_bio' ) == 'on' ) {
            ?>
            <div class="wpuf-author">
                <h3><?php _e( 'Author Info', 'wpuf' ); ?></h3>
                <div class="wpuf-author-inside odd">
                    <div class="wpuf-user-image"><?php echo get_avatar( $userdata->user_email, 80 ); ?></div>
                    <div class="wpuf-author-body">
                        <p class="wpuf-user-name"><a href="<?php echo get_author_posts_url( $userdata->ID ); ?>"><?php printf( esc_attr__( '%s', 'wpuf' ), $userdata->display_name ); ?></a></p>
                        <p class="wpuf-author-info"><?php echo $userdata->description; ?></p>
                    </div>
                </div>
            </div><!-- .author -->
            <?php
        }
    }

    /**
     * Delete a post
     *
     * Only post author and editors has the capability to delete a post
     */
    function delete_post() {
        $nonce = $_REQUEST['_wpnonce'];
        if ( !wp_verify_nonce( $nonce, 'wpuf_del' ) ) {
            die( "Security check" );
        }

        //check, if the requested user is the post author
        $maybe_delete = get_post( $_REQUEST['pid'] );

        if ( ($maybe_delete->post_author == $userdata->ID) || current_user_can( 'delete_others_pages' ) ) {
            wp_delete_post( $_REQUEST['pid'] );

            //redirect
            $redirect = add_query_arg( array('msg' => 'deleted'), get_permalink() );
            wp_redirect( $redirect );
        } else {
            echo '<div class="error">' . __( 'You are not the post author. Cheeting huh!', 'wpuf' ) . '</div>';
        }
    }

}

$wpuf_dashboard = new WPUF_Dashboard();